package com.lc.advertising.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.toast.ToastUtils;
import com.lc.advertising.R;
import com.lc.advertising.app.AppActivity;
import com.lc.advertising.dialog.InputDialog;
import com.lc.advertising.http.glide.GlideApp;
import com.lc.advertising.http.request.DriverEditApi;
import com.lc.advertising.http.request.GetCodeApi;
import com.lc.advertising.http.request.UpdateImageApi;
import com.lc.advertising.http.response.RegisterBean;
import com.lc.advertising.http.response.UpdateImageBean;
import com.lc.advertising.other.IntentKey;
import com.lc.advertising.util.CourseUtils;
import com.lc.advertising.util.GlideEngine;
import com.lc.advertising.util.SPUtil;
import com.lc.advertising.util.SettingBar;
import com.lc.advertising.widget.CountdownView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

public class PeopleDataActivity extends AppActivity {
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.img_head)
    ImageView imgHead;
    @BindView(R.id.sb_edit_name)
    SettingBar sbEditName;
    @BindView(R.id.sb_phone)
    SettingBar sbPhone;
    @BindView(R.id.et_register_code)
    AppCompatEditText etRegisterCode;
    @BindView(R.id.cv_register_countdown)
    CountdownView cvRegisterCountdown;
    private RxPermissions rxPermissions;
    private String img;

    //    mobile/personal/driver_edit
    @Override
    protected int getLayoutId() {
        return R.layout.activity_peopledata;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        rxPermissions = new RxPermissions(this);
        sbPhone.setRightText(getIntent().getStringExtra("mobile"));
        sbEditName.setRightText(getIntent().getStringExtra("nickname"));
        GlideApp.with(getActivity())
                .load(getIntent().getStringExtra("dheadimg"))
                .placeholder(R.mipmap.mine_default_avatar)
                .error(R.mipmap.mine_default_avatar)
                .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                .into(imgHead);
        img=getIntent().getStringExtra("dheadimg");
    }

    @OnClick({R.id.image_back, R.id.sb_edit_name, R.id.sb_phone, R.id.cv_register_countdown, R.id.btn_login_commit,R.id.img_head})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.img_head:
                carem();
                break;
            case R.id.sb_edit_name:
                new InputDialog.Builder(this)
                        // 标题可以不用填写
                        .setTitle(getString(R.string.personal_data_name_hint))
                        .setContent(sbEditName.getRightText())
                        //.setHint(getString(R.string.personal_data_name_hint))
                        //.setConfirm("确定")
                        // 设置 null 表示不显示取消按钮
                        //.setCancel("取消")
                        // 设置点击按钮后不关闭对话框
                        //.setAutoDismiss(false)
                        .setListener((dialog, content) -> {
                            if (!sbEditName.getRightText().equals(content)) {
                                sbEditName.setRightText(content);
                            }
                        })
                        .show();
                break;
            case R.id.sb_phone:
                new InputDialog.Builder(this)
                        // 标题可以不用填写
                        .setTitle(getString(R.string.personal_data_name_hint))
                        .setContent(sbPhone.getRightText())
                        //.setHint(getString(R.string.personal_data_name_hint))
                        //.setConfirm("确定")
                        // 设置 null 表示不显示取消按钮
                        //.setCancel("取消")
                        // 设置点击按钮后不关闭对话框
                        //.setAutoDismiss(false)
                        .setListener((dialog, content) -> {
                            if (!sbPhone.getRightText().equals(content)) {
                                sbPhone.setRightText(content);
                                tvName.setText(content);
                            }
                        })
                        .show();
                break;
            case R.id.cv_register_countdown:
                EasyHttp.post(this)
                        .api(new GetCodeApi()
                                .setMobile(sbPhone.getRightText().toString()))
                        .request(new HttpCallback<RegisterBean>(this) {

                            @Override
                            public void onSucceed(RegisterBean data) {
                                toast(data.getMessage());
                                if (data.getCode()==200){
                                    cvRegisterCountdown.start();
                                }

                            }

                            @Override
                            public void onFail(Exception e) {
                                super.onFail(e);
                                cvRegisterCountdown.start();
                            }
                        });
                break;
            case R.id.btn_login_commit:

                if (!getIntent().getStringExtra("mobile").equals(sbPhone.getRightText().toString())){
                    if (CourseUtils.isNotNullOrEmpty(etRegisterCode.getText().toString())&&etRegisterCode.getText().toString().length()==6){
                        driver_edit();
                    }else {
                        toast("请正确输入验证码");
                    }
                }else {
                    driver_edit();
                }

                break;
        }
    }

    private void driver_edit() {

        EasyHttp.post(this)
                .api(new DriverEditApi()
                        .setUid(SPUtil.get(this,IntentKey.UID,""))
                        .setDheadimg(img)
                        .setMobile(sbPhone.getRightText().toString())
                .setName(sbEditName.getRightText().toString())
                .setYzm(etRegisterCode.getText().toString()))
                .request(new HttpCallback<RegisterBean>(this) {



                    @Override
                    public void onSucceed(RegisterBean data) {
                        toast(data.getMessage());
                        if (data.getCode()==200){

                            finish();

                        }


                    }

                });
    }

    private void carem() {
        rxPermissions
                .request(Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            PictureSelector.create(PeopleDataActivity.this)
                                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                    .maxSelectNum(1)
                                    .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                                    .imageSpanCount(4)// 每行显示个数
                                    .selectionMode(PictureConfig.SINGLE)// 多选 or 单选PictureConfig.MULTIPLE : PictureConfig.SINGLE
                                    .isCamera(true)// 是否显示拍照按钮
                                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
//                                    .isEnableCrop(true)
//                                    .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                        } else {
                            ToastUtils.show("请求权限失败,相机不可用");
                        }
                    }
                });
    }
    private void getCommon_uploads(File headFile) {
        EasyHttp.post(this)
                .api(new UpdateImageApi()
                        .setPic(headFile))
                .request(new OnHttpListener<UpdateImageBean>() {

                    @Override
                    public void onSucceed(UpdateImageBean data) {
//
                        GlideApp.with(getActivity())
                                .load(data.getImg())
                                .placeholder(R.mipmap.mine_default_avatar)
                                .error(R.mipmap.mine_default_avatar)
                                .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                                .into(imgHead);
                        img = data.getImg();

                    }

                    @Override
                    public void onFail(Exception e) {

                    }
                });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            File headFile = new File(selectList.get(0).getRealPath());
            getCommon_uploads(headFile);


        }
    }
}
